package app.Disthanitian.thaistyle.EmerMez;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends Activity {

	static UrlEmerMez URLlink = new UrlEmerMez();
	public static final String url = URLlink.URLRegis;
	public static final String urlcheckmail = URLlink.getUrlcheckmail();
	public static final String urlactivatemail = URLlink.getUrlactivatemail();
	public static String result = "";
	public static String check = "";

	EditText edittext_email;
	EditText edittext_password;
	EditText edittext_repassword;
	EditText edittext_firstname;
	EditText edittext_lastname;
	EditText edittext_phone;
	EditText edittext_pincode;

	String email;
	int Check = 1;

	String check_mail;
	String check_pass;
	String check_repass;
	String check_firstname;
	String check_lastname;
	String check_phone;
	String check_pincode;

	protected void onCreate(Bundle saveInstanceState) {
		super.onCreate(saveInstanceState);
		setContentView(R.layout.register);

		Button bt_signup = (Button) findViewById(R.id.signup);
		
		edittext_email = (EditText) findViewById(R.id.edittext_email);
		edittext_email.requestFocus();
		bt_signup.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

				CheckValue();
				// Runbg a = new Runbg();
				// a.execute();

				// WebPageTask task = new WebPageTask();
				// task.execute();
				
				if (check_mail=="Y" && check_pass=="Y"&& check_repass=="Y" && check_firstname=="Y"
								&& check_lastname=="Y" && check_phone=="Y"
								&& check_pincode=="Y") {

							Runbg a = new Runbg();
							a.execute();

						}

			}
		});

	}

	public void CheckValue() {
		edittext_email = (EditText) findViewById(R.id.edittext_email);
		edittext_password = (EditText) findViewById(R.id.edittext_password);
		edittext_repassword = (EditText) findViewById(R.id.edittext_repassword);
		edittext_firstname = (EditText) findViewById(R.id.edittext_firstname);
		edittext_lastname = (EditText) findViewById(R.id.edittext_lastname);
		edittext_phone = (EditText) findViewById(R.id.edittext_phone);
		edittext_pincode = (EditText) findViewById(R.id.edittext_pincode);

		email = edittext_email.getText().toString().trim();
		String password = edittext_password.getText().toString().trim();
		String repassword = edittext_repassword.getText().toString().trim();
		String firstname = edittext_firstname.getText().toString().trim();
		String lastname = edittext_lastname.getText().toString().trim();
		String phone = edittext_phone.getText().toString().trim();
		String pincode = edittext_pincode.getText().toString().trim();

		
	if(Check==1){
		if (email.equals("")) {
			Toast.makeText(RegisterActivity.this, "Please Input Email!",
					Toast.LENGTH_SHORT).show();
		} else {
			boolean check = android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();

			if (!check) {
				Toast.makeText(RegisterActivity.this, "Invalid Email!",Toast.LENGTH_LONG).show();
			} else{
				check_mail="Y";
			}
			
		}

		if (password.equals("")) {
			Toast.makeText(RegisterActivity.this, "Please Input Password!",
					Toast.LENGTH_SHORT).show();

		} else {
			if (password.length() < 8 || repassword.length() < 8) {

				Toast.makeText(RegisterActivity.this,
						"Please Input Password Minimum 8 characters ",
						Toast.LENGTH_LONG).show();

			} else {
				check_pass = "Y";
			}
			if (!password.equals(repassword)) {
				Toast.makeText(
						RegisterActivity.this,
						"Please Input Password and Re-Type Password is not equal!",
						Toast.LENGTH_LONG).show();

			} else {
				check_repass = "Y";
			}
		}
		if (firstname.equals("")) {
			Toast.makeText(RegisterActivity.this, "Please Input Firstname!",
					Toast.LENGTH_SHORT).show();
		} else {
			check_firstname = "Y";
		}
		if (lastname.equals("")) {
			Toast.makeText(RegisterActivity.this, "Please Input Lastname!",
					Toast.LENGTH_SHORT).show();
		} else {
			check_lastname = "Y";
		}
		if (phone.equals("")) {
			Toast.makeText(RegisterActivity.this, "Please Input Phonenumber!",
					Toast.LENGTH_SHORT).show();
		} else {

			// String PhoneUser="0[8-9]{2}[0-9]{7}";
			Pattern pattern = Pattern.compile("0[8-9]{1}[0-9]{1}[0-9]{7}");
			// Pattern pattern = Pattern.compile("\\d{3}-\\d{7}");
			Matcher matcher = pattern.matcher(phone);
			if (!matcher.matches()) {
				Toast.makeText(RegisterActivity.this, "Invalid Phonenumber!",
						Toast.LENGTH_SHORT).show();
			}else{
				check_phone="Y";
			}
		}
		if (pincode.equals("")) {
			Toast.makeText(RegisterActivity.this, "Please Input Pincode!",
					Toast.LENGTH_SHORT).show();
		} else {
			if (pincode.length() > 4 || pincode.length() < 4) {
				Toast.makeText(RegisterActivity.this,
						"Invalid Pincode! Pincode 4 Number", Toast.LENGTH_SHORT)
						.show();
			} else {
				check_pincode = "Y";
			}
		}
    
	}

	}


	public String SendEmail() {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("email", email));

		return postDataSendEmail(urlactivatemail, nameValuePairs);

	}

	public String postDataSendEmail(String url,
			List<NameValuePair> nameValuePairs) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer("");
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));

			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			String page = sb.toString();
			return page;
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}
		return null;
	}

	public String checkemail() {
		edittext_email = (EditText) findViewById(R.id.edittext_email);

		String email = edittext_email.getText().toString().trim();
		List<NameValuePair> nameValuePairs = null;
		nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("email", email));

		return postDataCheck(urlcheckmail, nameValuePairs);

	}

	public String postDataCheck(String url, List<NameValuePair> nameValuePairs) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer("");
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));

			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			String page = sb.toString();
			return page;
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}
		return null;
	}

	public String signUp() {
		edittext_email = (EditText) findViewById(R.id.edittext_email);
		edittext_password = (EditText) findViewById(R.id.edittext_password);
		edittext_repassword = (EditText) findViewById(R.id.edittext_repassword);
		edittext_firstname = (EditText) findViewById(R.id.edittext_firstname);
		edittext_lastname = (EditText) findViewById(R.id.edittext_lastname);
		edittext_phone = (EditText) findViewById(R.id.edittext_phone);
		edittext_pincode = (EditText) findViewById(R.id.edittext_pincode);

		email = edittext_email.getText().toString().trim();
		String password = edittext_password.getText().toString().trim();
		String repassword = edittext_repassword.getText().toString().trim();
		String firstname = edittext_firstname.getText().toString().trim();
		String lastname = edittext_lastname.getText().toString().trim();
		String phone = edittext_phone.getText().toString().trim();
		String pincode = edittext_pincode.getText().toString().trim();

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("email", email));
		nameValuePairs.add(new BasicNameValuePair("password", password));
		nameValuePairs.add(new BasicNameValuePair("repassword", repassword));
		nameValuePairs.add(new BasicNameValuePair("firstname", firstname));
		nameValuePairs.add(new BasicNameValuePair("lastname", lastname));
		nameValuePairs.add(new BasicNameValuePair("phone", phone));
		nameValuePairs.add(new BasicNameValuePair("pincode", pincode));

		return postData(url, nameValuePairs);

	}

	public String postData(String url, List<NameValuePair> nameValuePairs) {

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer("");
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));

			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			String page = sb.toString();
			return page;
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}
		return null;
	}

	protected class WebPageTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {

			result = signUp();

			return result;
		}

		protected void onPostExecute(String result) {

			// Toast.makeText(RegisterActivity.this,result +
			// "Hi",Toast.LENGTH_LONG).show();

			if (result.trim().equals("ok")) {
				Toast.makeText(RegisterActivity.this, "Sign up success!",
						Toast.LENGTH_LONG).show();

				RunSendEmail b = new RunSendEmail();
				b.execute();

				// Call send Email //Please Confirm Your Email
			} else if (result.trim().equals("fail")) {
				Toast.makeText(RegisterActivity.this, "Sign up fail",
						Toast.LENGTH_LONG).show();
			} else if (result.trim().equals("email")) {
				Toast.makeText(RegisterActivity.this, "email is registered",
						Toast.LENGTH_LONG).show();
			}

		}

	}

	protected class Runbg extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {

			result = checkemail();

			return result;
		}

		protected void onPostExecute(String result) {
			if (result.trim().equals("email")) {
				Toast.makeText(RegisterActivity.this,
						"email is already existed ", Toast.LENGTH_LONG).show();
				        check_mail ="";
				        CheckValue();
			} else {

				 WebPageTask task = new WebPageTask();
				 task.execute();
				 
			/*	check_mail="";
				check_pass="";
			    check_repass="";
				check_firstname="";
				check_lastname="";
				check_phone="";
				check_pincode=""; */
			}

		}
	}

	protected class RunSendEmail extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {

			result = SendEmail();

			return result;
		}

		// Result send activate email
		protected void onPostExecute(String result) {

			// Toast.makeText(RegisterActivity.this,result +
			// "Hi",Toast.LENGTH_LONG).show();
			if (result.trim().equals("ok")) {
				Toast.makeText(RegisterActivity.this,
						"Send Email !Please Activate Account Your Email ",
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(RegisterActivity.this, "Cannot Send Email ",
						Toast.LENGTH_LONG).show();
			}

		}

	}

}
